ActiveAdmin.register Coach do
  menu label: '教练'
  filter :name
  filter :en_name
  filter :contact
  filter :city, label: '工作城市'
  filter :created_at, label: '注册日期'

  actions :index

  index download_links: [:csv] do
    selectable_column
    column :id
    column :uuid
    column :name do |c|
      truncate(c.name, length: 18)
    end
    column :en_name do |c|
      truncate(c.en_name, length: 18)
    end
    column :city
    column :level
    column :kind
    column :contact
  end

  show do
    attributes_table do
      row :name
      row :en_name
      row :city
      row :level
      row :kind
      row :contact
    end
  end
  controller do
    def index
      if params[:format].eql?("csv")
        csv = CSV.generate(headers: true) do |row|
          row << %w(编号 工号 中文名 英文名 工作城市 工作类型 性别 电话 注册时间 包课 离职)
          Coach.pluck(Arel.sql("id, employee_id, name, en_name, city, CONCAT(coaches.kind, '/', coaches.level) AS kind, gender, contact, created_at, standard_lesson, resignation")).each { |columns|
            row << columns
          }
        end
        bom = "\xFF\xFE".force_encoding("UTF-16LE")
        send_data((bom + csv.encode("UTF-16LE")), type: Mime[:csv], disposition: "attachment; filename=教练信息.csv")
      else
        index!
      end
    end
  end
end